import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
//封装一个函数用于判断当前地址是否存在载权限数组中
function hasUrl(url,next){
  let result=JSON.parse(sessionStorage.getItem('userinfo')).menus_url.some((item)=>url==item)
  if(result){
    next()
  }else{
    next('/home')
  }
}
//封装一个二级路由地址
export const indexRoutes=[  
  {
    path:'/menu',
    component:()=>import('../views/Menu/menu.vue'),
    meta:{
      title:'菜单管理'
    },
    beforeEach(to,from,next){
      hasUrl('/menu',next)
    }
  },
  {
    path:'/role',
    component:()=>import('../views/Role/role.vue'),
    meta:{
      title:'角色管理'
    },
    beforeEach(to,from,next){
      hasUrl('/role',next)
    }
  },
  {
    path:'/user',
    component:()=>import('../views/Manage/user.vue'),
    meta:{
      title:'管理员管理'
    },
    beforeEach(to,from,next){
      hasUrl('/user',next)
    }
  },
  {
    path:'/cate',
    component:()=>import('../views/Cate/cate.vue'),
    meta:{
      title:'商品分类'
    },
    beforeEach(to,from,next){
      hasUrl('/cate',next)
    }
  },
  {
    path:'/goodsspace',
    component:()=>import('../views/goodsspace/goodsspace.vue'),
    meta:{
      title:'商品规格'
    },
    beforeEach(to,from,next){
      hasUrl('/goodsspace',next)
    }
  },
  {
    path:'/goods',
    component:()=>import('../views/goods/goods.vue'),
    meta:{
      title:'商品管理'
    },
    beforeEach(to,from,next){
      hasUrl('/goods',next)
    }
  },
  {
    path:'/member',
    component:()=>import('../views/member/member.vue'),
    meta:{
      title:'会员管理'
    },
    beforeEach(to,from,next){
      hasUrl('/member',next)
    }
  },
  {
    path:'/pic',
    component:()=>import('../views/pic/pic.vue'),
    meta:{
      title:'轮播图管理'
    },
    beforeEach(to,from,next){
      hasUrl('/pic',next)
    }
  },
  {
    path:'/seckill',
    component:()=>import('../views/seckill/seckill.vue'),
    meta:{
      title:'限时秒杀'
    },
    beforeEach(to,from,next){
      hasUrl('/seckill',next)
    }
  }
]
const routes = [
  {
    path:'/login',
    component:()=>import('../pages/login.vue')
  },
  {
    path:'/index',
    component:()=>import('../pages/index.vue'),
    children:[
      {
        path:'/home',
        component:()=>import('../views/home.vue')
      },
      ...indexRoutes,
      {
        path:'',
        redirect:'/home'
      }
    ]
  },
  {
    path:'*',
    redirect:'/index'
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
//封装一个全局登录拦截的方法
/*
  步骤:
  1.如果地址访问的是登录  让它通过
  2.如果访问的不是登录页  这个时候要判断是否登录 如果登录了 让它通过
  3.以上条件都不符合的时候  就强制跳转到登录
  利用什么方法
  路由导航守卫 前置守卫 钩子函数
*/
router.beforeEach((to,from,next)=>{
  if(to.path=='/login'){
    next()
    return
  }
  if(sessionStorage.getItem('userinfo')){
    next()
    return
  }
  next('/login')
})
export default router
